<template>
<div>
  <div  class="mod-config" id="mod-config-id">
    <div v-if="isAuth('regionManage:paging')" class="div-s" id="div-s-id">
      <el-form :model="params" :label-position="labelPosition" ref="queryFormRef" :inline="true" label-width="70px" class="queryFormed">
        <el-row class="row-s">
          <el-col :span="6">
            <el-form-item label="所在区域" prop="areaId"  >
              <el-select v-model="areaSelectValue" placeholder="请选择区域"  @clear="clearArea" @focus="showSelectAreaDialog" @change="clickSearch" clearable>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="管理人" prop="managerId">
              <el-select v-model="params.managerId" placeholder="请选择管理人" @clear="clickSearch" @focus="getManagerList" @change="clickSearch" filterable  clearable>
                <el-option
                  v-for="item in managerOptions"
                  :key="item.id"
                  :label="item.nickName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item  prop="distributionFlag">
              <el-checkbox v-model="params.distributionFlag" true-label="1" false-label="0" @change="clickSearch"   clearable>未分配区域</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col class="col-right" :span="6">
            <el-form-item class="item-all">
              <el-button class="buttonItem" size="mini" plain @click="clickReset">重 置</el-button>
              <el-button class="buttonItem" size="mini" type="primary" @click="clickSearch">搜 索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="div-e" id="div-e-id">
      <div class="div-inquire" id="div-inquire-id">
        <div class="in-t">
          <div class="in-ts"></div>
          <h3 >区域管理</h3>
        </div>
        <div  class="div-button">
          <el-button v-if="isAuth('regionManage:area:save')" size="mini" type="primary" icon="el-icon-plus" @click="showAddCityDialog">新增城市</el-button>
          <el-button v-if="isAuth('regionManage:area:save')" size="mini" type="primary" icon="el-icon-plus" @click="showAddAreaDialog">新增地区</el-button>
          <el-button v-if="isAuth('regionManage:allocate')" size="mini" type="primary" icon="" @click="showAllocateRegionDialog">分配区域管理人</el-button>
          <el-button v-if="isAuth('regionManage:export')"  size="mini" type="primary" icon="el-icon-upload2" @click="clickExport">数据导出</el-button>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        :max-height="table.tableHeight+50"
        :header-cell-style="{background:'#F5F7FA'}"
        :tree-props="{children: 'children'}"
        row-key="id"
        style="width: 100%"
        v-loading="dataListLoading"
        @row-click="ClickRowHandle"
        @selection-change="handleSelectionChange"
        fit>
<!--        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          label="城市"
          width="200"
          prop="cityName"
          align="center">
        </el-table-column>
        <el-table-column
          prop="cityManagerName"
          label="管理人(城市)"
          width="200"
          align="center">
        </el-table-column>-->
        <el-table-column
          prop="name"
          label="区域"
          align="center">
        </el-table-column>
        <el-table-column
          prop="managerName"
          label="管理人"

          align="center">
        </el-table-column>
        <el-table-column
          prop="dealCustomerAmount"
          label="企业成交数量"
          align="center">
        </el-table-column>
        <el-table-column
          prop="unDealCustomerAmount"
          label="非成交数量"
          align="center">
        </el-table-column>
        <el-table-column
          prop=""
          label="总数量"
          align="center">
          <template slot-scope="scope">
            {{(+scope.row.dealCustomerAmount) + (+scope.row.unDealCustomerAmount)}}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center">
          <template slot-scope="scope">
            <el-button v-if="isAuth('regionManage:update')" type="text" size="mini" class="btn-text-normal" @click="showUpdateAreaDialog(scope.row)">修改</el-button>
            <el-button v-if="isAuth('regionManage:delete')" type="text" size="mini" class="btn-text-danger" @click="clickDelete(scope.row)">删除</el-button>
            <el-button v-if="isAuth('regionManage:cancelAllocate') && scope.row.managerName"  type="text" size="mini" class="btn-text-danger" @click="takeBackRegionalReq(scope.row)">取消分配</el-button>
          </template>
        </el-table-column>
      </el-table>
<!--      <el-pagination
        @size-change="changePageSize"
        @current-change="turnToPage"
        :current-page="queryInfo.pageIndex"
        :page-sizes="[5, 10, 20, 50, 100, 200]"
        :page-size="queryInfo.pageSize "
        layout="total, prev, pager, next, sizes, jumper"
        :total="totalPage"
        id="div-e-paging-id">
      </el-pagination>-->
    </div>
  </div>
  <el-dialog
    title=""
    :visible.sync="allocateRegionDialogVisible"
    width="30%">
    <h3 slot='title'>分配</h3>
    <div>
      <el-form :model="regionForm" :rules="regionFormRules"  ref="regionFormRefs" label-width="100px">
        <el-row >
          <el-col :span="22" :offset="1">
            <el-form-item label="城市" prop="cityId"  >
              <el-select style="width: 95%" v-model="regionForm.cityId"  placeholder="请选择城市" @focus="getCityList" @change="changeCityOption" filterable >
                <el-option v-for="item in cityOptions"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                  <span >{{item.name}}</span>
                  <span style="font-weight: bold">{{item.managerName ? `(${item.managerName})` : ''}}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="22" :offset="1">
            <el-form-item label="区域" prop="" >
              <el-select style="width: 95%" v-model="regionForm.areaId" placeholder="请选择区域" filterable  multiple clearable collapse-tags>
                <el-option v-for="item in areaOptions"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                  <span>{{item.name}}</span>
                  <span style="font-weight: bold">{{item.managerName ? `(${item.managerName})` : ''}}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="22" :offset="1">
            <el-form-item  label="管理人" prop="userIdList">
              <el-select style="width: 95%" v-model="regionForm.userIdList"   placeholder="请选择管理人" @focus="getManagerList"  filterable clearable>
                  <el-option
                    v-for="item in managerOptions"
                    :key="item.id"
                    :label="item.nickName"
                    :value="item.id">
                  </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="22" :offset="1">
            <el-form-item label="有效时间" prop="endTime" clearable>
            <el-row>
              <el-col :span="16">
                <el-date-picker
                  v-model="regionForm.endTime"
                  value-format="yyyy-MM-dd"
                  type="date"
                  placeholder="请选择有效时间"
                  style="width: 100%"
                :disabled="regionForm.alwaysFlag === 1">
                </el-date-picker>
              </el-col>
              <el-col :span="6" :offset="1"><el-checkbox v-model="regionForm.alwaysFlag" :true-label="1" :false-label="0" @change="changeAlwaysFlag">是否永久</el-checkbox></el-col>
            </el-row>
        </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
    <el-button @click="allocateRegionDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="clickAllocateRegion">确 认</el-button>
  </span>
  </el-dialog>

  <el-dialog
    title=""
    :visible.sync="addCityDialogVisible"
    width="30%">
    <h3 slot='title'>新增城市</h3>
    <div>
      <el-form :model="regionForm" :rules="regionFormRules"   ref="addCityFormRefs" label-width="100px" >
        <el-row >
          <el-col :span="22" :offset="1">
            <el-form-item label="城市" prop="cityName" >
              <el-input v-model="regionForm.cityName"  placeholder="请输入城市名称" >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="addCityDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addCity">确 定</el-button>
    </span>
  </el-dialog>

  <el-dialog
    title="提示"
    :visible.sync="addAreaDialogVisible"
    width="30%">
    <h3 slot='title'>新增地区</h3>
    <div>
      <el-form :model="regionForm" :rules="regionFormRules" ref="addAreaFormRefs" label-width="100px">
        <el-row >
          <el-col :span="22" :offset="1">
            <el-form-item label="城市" prop="cityId"  >
              <el-select v-model="regionForm.cityId"  placeholder="请选择城市" style="width:100%" >
                <el-option v-for="item in cityOptions"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="22" :offset="1">
            <el-form-item label="区域" prop="areaName" >
              <el-input v-model="regionForm.areaName" placeholder="请输入区域" >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="addAreaDialogVisible = false;clickCancel">取 消</el-button>
      <el-button type="primary" @click="addArea">确 定</el-button>
    </span>
  </el-dialog>

  <el-dialog
    title="提示"
    :visible.sync="updateAreaDialogVisible"
    width="30%"
  @closed="()=>{this.regionForm.cityName = null;this.regionForm.areaName = null}">
    <h3 slot='title'>修改地区</h3>
    <div>
      <el-form :model="regionForm"  :rules="regionFormRules"  ref="updateAreaFormRefs" label-width="100px">
        <el-row v-if="regionForm.cityName">
          <el-col :span="22" :offset="1">
            <el-form-item label="城市" prop="cityName"  >
              <el-input v-model="regionForm.cityName"  placeholder="" :disabled="regionForm.typeId !== 2">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="regionForm.areaName">
          <el-col :span="22" :offset="1">
            <el-form-item label="区域" prop="areaName" >
              <el-input v-model="regionForm.areaName" placeholder="" :disabled="regionForm.typeId !== 3">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="updateAreaDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="updateArea">确 定</el-button>
    </span>
  </el-dialog>

  <el-dialog
    title=""
    :visible.sync="selectAreaDialogVisible"
    top="20vh"
    width="35%">
      <h3 slot="title">
        选择地区
      </h3>
    <div style="border: 1px solid #DDDDDD;border-radius: 2px;height: 30vh;overflow: auto;margin: 0 40px 28px 40px;padding: 13px 20px">
      <el-tree :data="areaTreeData" :props="areaTreeProps" @node-click="areaHandleNodeClick" ></el-tree>
    </div>
    <span style="display: flex;justify-content: center;">
        <el-button @click="selectAreaDialogVisible = false">取 消</el-button>
<!--        <el-button type="primary" @click="selectAreaDialogVisible = false">确 认</el-button>-->
        <el-button type="primary" @click="clickSelectAreaSearch">确 认</el-button>
      </span>
  </el-dialog>
</div>
</template>

<script>
import BasePaging from '../../common/BasePaging'
import ElTreeSelect from '../../../components/treeSelect/index.vue'
import {isAuth} from '../../../utils'
import {exportData} from '../../../api/customer/commom'
import {
  getAreaTree,
  getRegionList,
  deleteRegion,
  addRegion,
  allocateRegion, updateRegion
} from '../../../api/customer/region'
import {getUserList} from '../../../api/user'
import {tackBackRegional} from '../../../api/customer/regionalListManage'

export default {
  components: {ElTreeSelect},
  extends: BasePaging,
  name: 'region-manage',
  created () {
    if (this.isAuth('regionManage:paging')) { this.paging() }
    this.getAreaTree()
  },
  data () {
    return {
      labelPosition: 'right',
      dataListLoading: false,
      regionDialogVisible: false,
      addCityDialogVisible: false,
      addAreaDialogVisible: false,
      allocateRegionDialogVisible: false,
      updateAreaDialogVisible: false,
      selectAreaDialogVisible: false,
      areaSelectValue: '',
      params: {
        areaId: '',
        managerId: '',
        distributionFlag: 0
      },
      areaTreeData: [],
      areaTreeProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      cityOptions: [],
      areaOptions: [],
      managerOptions: [],
      regionForm: {
        // dialogType:allocate,city,area,areaUpdate
        'id': '',
        'dialogType': 'allocate',
        'title': '',
        'cityId': '',
        'areaId': '',
        'userIdList': [],
        // 新增区域使用，分配该模块内固定为1
        'typeId': 2,
        'endTime': '',
        // 新增城市
        'cityName': '',
        'areaName': '',
        // 分配时间是否永久
        'alwaysFlag': 1
      },
      regionFormRules: {
        cityId: [{ required: true, message: '请选择城市', trigger: 'change' }],
        areaId: [{ required: true, message: '请选择地区', trigger: 'change' }],
        userIdList: [{ required: true, message: '请选择管理人', trigger: 'change' }],
       // endTime: [{ required: true, message: '请选择有效时间', trigger: 'change' }],
        cityName: [{ required: true, message: '请输入城市名称', trigger: 'blur' }],
        areaName: [{ required: true, message: '请输入区域名称', trigger: 'blur' }]
      },
      treeData: {

      },
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  methods: {
    isAuth (auth) {
      return isAuth(auth)
    },
    handleSelectionChange () {},
    initParmas () {
      this.areaId = ''
      this.managerId = ''
      this.distributionFla = 0
    },
/*    paging () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/ent/area/paging'),
        method: 'post',
        data: this.$http.adornData({
          'conditions': {
            'areaId': this.params.areaId,
            'managerId': this.params.managerId,
            'distributionFlag': this.params.distributionFlag
          },
          'inOrder': '',
          'orderBy': '',
          'pageNum': this.queryInfo.pageIndex,
          'pageSize': this.queryInfo.pageSize
        })
      }).then(({data}) => {
        this.tableData = data.data.records
        this.totalPage = data.data.total
        this.dataListLoading = false
      })
    }, */
    paging () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/ent/area/tree/list'),
        method: 'post',
        data: this.$http.adornData({
          'areaId': this.params.areaId,
          'managerId': this.params.managerId,
          'distributionFlag': this.params.distributionFlag
        })
      }).then(({data}) => {
        this.tableData = data.data
        this.dataListLoading = false
      })
    },
    clickReset () {
      this.$refs['queryFormRef'].resetFields()
      this.areaSelectValue = ''
      this.paging()
    },
    getAreaTree () {
      getAreaTree({'actionId': 1}, (data) => { this.areaTreeData = data.data })
    },
    getAreaList () {
      getRegionList({
        'name': '',
        'parentId': this.regionForm.cityId,
        'typeId': 3,
        'actionId': 1
      }, (data) => { this.areaOptions = data.data })
    },
    getCityList () {
      getRegionList({
        'name': '',
        'parentId': '',
        'typeId': 2,
        'actionId': 1
      }, (data) => { this.cityOptions = data.data })
    },
    getManagerList () {
      getUserList({
        'nickName': '',
        'name': '',
        'areaManagerFlag': 1
      }, (data) => { this.managerOptions = data.data })
    },
    changeCityOption (val) {
      this.getAreaList()
      this.regionForm.areaId = ''
    },
    initRegionForm () {
      this.regionForm.name = ''
      this.regionForm.id = ''
      this.regionForm.cityId = ''
      this.regionForm.cityName = ''
      this.regionForm.areaId = ''
      this.regionForm.userIdList = []
      this.regionForm.typeId = ''
      this.regionForm.endTime = ''
      this.regionForm.areaName = ''
    },
    clickCancel () {
      this.initRegionForm()
    },
    dialogTypeIs (dialogType) {
      return this.regionForm.dialogType === dialogType
    },
    showAllocateRegionDialog () {
      // this.getCityList()
      // this.getAreaList()
      this.initRegionForm()
      this.allocateRegionDialogVisible = true
    },
    showAddCityDialog () {
      this.regionForm.cityName = ''
      this.addCityDialogVisible = true
    },
    showAddAreaDialog () {
      this.getCityList()
      this.regionForm.cityId = ''
      this.regionForm.areaName = ''
      this.addAreaDialogVisible = true
    },
    showUpdateAreaDialog (row) {
      if (row.typeId === 2) {
        this.regionForm.cityName = row.name
      } else if (row.typeId === 3) {
        this.regionForm.areaName = row.name
      }
      this.regionForm.cityId = row.cityId
      this.regionForm.typeId = row.typeId
      this.regionForm.id = row.id
      this.updateAreaDialogVisible = true
    },
    nodeClick () {

    },
    clickSearch () {
      this.queryInfo.pageIndex = 1
      this.paging()
    },
    clickDelete (region) {
      this.$confirm(`确认要删除地区 ${region.name} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRegion(region.id, () => { this.paging() })
      })
    },
    addCity () {
      this.$refs.addCityFormRefs.validate((valid) => {
        if (valid) {
          addRegion({
            'typeId': 2,
            'name': this.regionForm.cityName,
            'sort': '',
            'parentId': ''
          }, () => { this.paging() })
          this.addCityDialogVisible = false
        } else {
          return false
        }
      })
    },
    addArea () {
      this.$refs.addAreaFormRefs.validate((valid) => {
        if (valid) {
          addRegion({
            'typeId': 3,
            'name': this.regionForm.areaName,
            'sort': '',
            'parentId': this.regionForm.cityId
          }, () => { this.paging() })
          this.addAreaDialogVisible = false
        } else {
          return false
        }
      })
    },
    clickAllocateRegion () {
      this.$refs.regionFormRefs.validate((valida) => {
        if (valida) {
          allocateRegion({
            'cityId': this.regionForm.cityId,
            'areaIdList': this.regionForm.areaId ? this.regionForm.areaId : [],
            // 用户列表是数组形式
            'userIdList': [this.regionForm.userIdList],
            'typeId': 1,
            'endTime': this.regionForm.endTime,
            'alwaysFlag': this.regionForm.alwaysFlag
          }, () => {
            this.paging()
            this.$message.success('分配成功!')
          })
          this.allocateRegionDialogVisible = false
        } else {
          return false
        }
      })
    },
    updateArea () {
      let name = ''
      let parentId = ''
      let typeId = ''
      let id = ''
      // 根据选择的typeId判断是对城市修改还是对区域修改，每次只能修改一项
      if (this.regionForm.typeId === 3) {
        id = this.regionForm.id
        typeId = this.regionForm.typeId
        name = this.regionForm.areaName
        parentId = this.regionForm.cityId
      } else if (this.regionForm.typeId === 2) {
        id = this.regionForm.id
        typeId = this.regionForm.typeId
        name = this.regionForm.cityName
      }
      this.$refs.updateAreaFormRefs.validate((valida) => {
        if (valida) {
          updateRegion({
            'id': id,
            'typeId': typeId,
            'name': name,
            'sort': '',
            'parentId': parentId
          }, () => { this.paging() })
          this.updateAreaDialogVisible = false
        } else {
          return false
        }
      })
    },
    clearArea () {
      this.params.areaId = ''
      this.clickSearch()
    },
    showSelectAreaDialog () {
      this.getAreaTree()
      this.selectAreaDialogVisible = true
    },
    areaHandleNodeClick (nodeObj, node) {
      this.areaSelectValue = node.data.name
      this.params.areaId = node.data.id
    },
    clickExport () {
      exportData('/ent/area/export', {...this.params}, '区域管理')
    },
    changeAlwaysFlag (val) {
      if (val === 1) {
        this.regionForm.endTime = ''
      }
    },
    clickSelectAreaSearch () {
      this.clickSearch()
      this.selectAreaDialogVisible = false
    },
    // 点击表格行，展开行
    ClickRowHandle (row, clo, event) {
      let tableRefs = this.$refs.multipleTable
      tableRefs.toggleRowExpansion(row)
    },
    takeBackRegionalReq (row) {
      console.log('row', row)
      this.$confirm(`确定取消 “${row.name}” 的管理人`, '提示', {
        confirmButtonText: '确 定',
        cancelButtonText: '取 消',
        type: 'warning'
      }).then(() => {
        let formData = {}
        if (row.typeId === 3) {
          // 区域取消
          formData['cityId'] = row.parentId
          formData['areaIdList'] = [row.id]
        } else if (row.typeId === 2) {
          // 城市取消
          formData['cityId'] = row.id
          formData['areaIdList'] = []
        }
        // typeId 1区域管理 2区域销售
        formData['typeId'] = 1
        tackBackRegional(formData, () => { this.paging() }, () => {})
      })
    }

  }
}
</script>

